package com.leyou.user.controller;

import com.leyou.common.exception.domain.LyException;
import com.leyou.user.domain.User;
import com.leyou.user.dto.UserDTO;
import com.leyou.user.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.validation.BindingResult;
import org.springframework.validation.FieldError;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletResponse;
import javax.validation.Valid;
import java.util.stream.Collectors;

/**
 * 校验用户名或手机号是否可用
 */
@RestController
@RequestMapping
public class UserController {
    @Autowired
    private UserService userService;
    @GetMapping("/check/{data}/{type}")
    public ResponseEntity<Boolean>checkUsernameOrPhone(
            @PathVariable("data") String data,
            @PathVariable("type") Integer type){
        Boolean result=userService.checkUsernameOrPhone(data,type);
        return ResponseEntity.ok(result);


    }

    /**
     * 发送短信验证码，验证手机短信吗
     */

    @PostMapping("/code")
    public ResponseEntity<Void>sendCode(@RequestParam("phone") String phone){
        userService.sendCode(phone);
        return ResponseEntity.status(HttpStatus.NO_CONTENT).build();

    }

    /**
     * 完成注册
     */
    //BindingResult 必须在@Valid注解参数后面
    @PostMapping("/register")
    public ResponseEntity<Void>register(@Valid User user, BindingResult result, @RequestParam("code")String code){
        //判断是否有异常
        if(result.hasErrors()){
            //收集所有的异常信息
            String errorStr = result.getFieldErrors().stream()
                    .map(FieldError::getDefaultMessage)
                    .collect(Collectors.joining("|"));
            //抛出自定义异常
            throw new LyException(500, errorStr);
        }
        userService.register(user,code);
        return ResponseEntity.status(HttpStatus.CREATED).build();
    }


    //在用户微服务中提供根据用户名和密码查询用户的接口提供处理器
    @GetMapping("/query")
    public ResponseEntity<UserDTO>queryUser
    (@RequestParam("username") String username,
     @RequestParam("password") String password){
        UserDTO userDTO=userService.queryUser(username,password);
        return ResponseEntity.ok(userDTO);
    }



}
